package com.ourcraft.informationcollectionsystem.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.ourcraft.informationcollectionsystem.entity.User;
import com.ourcraft.informationcollectionsystem.service.user.UserService;
import com.ourcraft.informationcollectionsystem.utils.response.Result;
import com.ourcraft.informationcollectionsystem.utils.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 处理用户模块相关的请求
 *
 * @author Z0136
 * @since 2023-10-29
 */
@RequestMapping("user/")
@RestController
@CrossOrigin()
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 处理‘user/login’接口的前端请求，用户请求登录
     *
     * @param param 包含登录用户的账号和密码
     * @return 登录成功：登录用户的信息和Token；登录失败：登录失败信息
     */
    @PostMapping("login")
    public Result<User> userLogin(@RequestBody JSONObject param) {
        User user = userService.login(param.getInteger("userId"), param.getString("userPassword"));
        if (user == null) return new Result<>(ResultCode.FAIL, "账号或密码错误");
        else {
            user.setUserPassword(null);
            return Result.success(user);
        }
    }

    /**
     * 处理‘user/info’接口的前端请求，用户根据Token获取用户信息
     *
     * @param token 用户Token
     * @return token对应的用户信息
     */
    @GetMapping("info")
    public Result<User> userInfo(@RequestParam String token) {
        return Result.success(userService.getUserInfo(token));
    }

    /**
     * 处理‘user/logout’接口的前端请求，用户退出登录
     * （未进行处理）
     *
     * @return 返回成功
     */
    @PostMapping("logout")
    public Result<Boolean> userLogout() {
        return Result.success();
    }

    /**
     * 处理‘user/testConnection’接口的前端请求，用于前端测试连接
     *
     * @return 返回成功
     */
    @GetMapping("testConnection")
    public Result<Boolean> testConnection() {
        return Result.success();
    }

    @PostMapping("changePassword")
    public Result<Boolean> changePassword(@RequestBody JSONObject param) {
        return userService.changePassword(param.getString("oldPassword"), param.getString("newPassword"), param.getInteger("userId")) ? Result.success() : Result.fail("原密码错误！");
    }
}
